package com.tc.juc.design;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class TestJiaoTiWaitNotify {

    public static void main(String[] args) {
        WaitNotify waitNotify = new WaitNotify(10,2);
        Thread t1 = new Thread(()->{waitNotify.print("a", 1, 2);},"t1");
        Thread t2 = new Thread(()->{waitNotify.print("b", 2, 3);},"t2");
        Thread t3 = new Thread(()->{waitNotify.print("c", 3, 1);},"t3");
        t1.start();
        t2.start();
        t3.start();
    }
}
class WaitNotify{
    int loopNum = 5;
    int flag = 1;

    public WaitNotify(int loopNum, int flag) {
        this.loopNum = loopNum;
        this.flag = flag;
    }

    public void print(String str, int waitFlag, int nextFlag){
        for (int i=0;i<loopNum;i++){
            synchronized (this){
                while (flag != waitFlag){
                    try {
                        this.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.print(str);
                flag = nextFlag;
                this.notifyAll();
            }
        }
    }
}
